package com.oneplatform.controller;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.mendmix.common.annotation.ApiMetadata;
import com.mendmix.common.constants.PermissionLevel;
import com.mendmix.common.http.HttpRequestEntity;
import com.mendmix.common.model.WrapperResponse;
import com.mendmix.gateway.CurrentSystemHolder;
import com.mendmix.gateway.model.BizSystemModule;

/**
 * 
 * 
 * <br>
 * Class Name   : SchedulerMgtController
 *
 * @author <a href="mailto:vakinge@gmail.com">vakin</a>
 * @version 1.0.0
 * @date Feb 12, 2022
 */
@RestController
@RequestMapping("/schedule")
public class SchedulerMgtController {

	@SuppressWarnings("rawtypes")
	@GetMapping("jobs")
	@ApiMetadata(permissionLevel = PermissionLevel.LoginRequired,actionLog = false)
	public WrapperResponse<List<Map>> getJobList(@RequestParam(name = "serviceId",required = false) String serviceId){
		List<Map> list = new ArrayList<>();
		Collection<BizSystemModule> modules = CurrentSystemHolder.getModules();
		for (BizSystemModule module : modules) {
			if(serviceId != null && !serviceId.equals(module.getServiceId())) {
				continue;
			}
			list.addAll(fetchModuleJobs(module));
		}
		return WrapperResponse.success(list);
	}

	@SuppressWarnings("rawtypes")
	private List<Map> fetchModuleJobs(BizSystemModule module) {
		
		List<Map> jobs;
		try {
			String url = module.getHttpBaseUri() + "/scheduler/status";
			jobs = HttpRequestEntity.get(url).backendInternalCall().execute().toList(Map.class,"jobs");
		} catch (Exception e) {
			jobs = new ArrayList<>(0);
		}
		return jobs;
	}
}
